package api.cie.rss.dal;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

/**
 * The class to manipulate with the Parameter table in the database
 * @author STL-API
 *
 */
public class ParameterDAL {
	public static final String KEY_PARAMKEY = "key";
	public static final String KEY_PARAMVALUE = "value";
	public static final String KEY_ROWID = "_id";
	
	public static final String DATABASE_TABLE = "Parameter";
	private SQLiteDatabase database;
	
	public ParameterDAL(DatabaseAdapter dbAdapter) {
		database = dbAdapter.getDatabase();
	}
	
	/**
	 * Create a new Parameter. If the Parameter is successfully created, return the new
	 * rowId for that Parameter, otherwise return a -1 to indicate failure.
	 */
	public long createParameter(String key, String value) {
		ContentValues initialValues = createContentValues(key, value);

		return database.insert(DATABASE_TABLE, null, initialValues);
	}
	
	private ContentValues createContentValues(String key, String value) {
		ContentValues values = new ContentValues();
		values.put(KEY_PARAMKEY, key);
		values.put(KEY_PARAMVALUE, value);
		
		return values;
	}
	
	/**
	 * Update a parameter in the database
	 * @param key
	 * @param newValue
	 */
	public void updateParameter(String key, String newValue) {
		ContentValues values = new ContentValues();
		values.put(KEY_PARAMVALUE, newValue);
		database.update(DATABASE_TABLE, values, KEY_PARAMKEY+" = '" + key + "'", null);
	}
	
	/**
	 * Deletes Parameter
	 */
	public boolean deleteParameter(long rowId) {
		return database.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	/**
	 * Return a Cursor over the list of all parameters in the database
	 * 
	 * @return Cursor over all parameters
	 */
	public Cursor fetchAllParameters() {
		return database.query(DATABASE_TABLE, new String[] { KEY_ROWID,
				KEY_PARAMKEY, KEY_PARAMVALUE }, null, null, null,
				null, null);
	}

	/**
	 * Return a Cursor positioned at the defined Parameter
	 */
	public Cursor fetchParameter(long rowId) throws SQLException {
		Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] {
				KEY_ROWID, KEY_PARAMKEY, KEY_PARAMVALUE },
				KEY_ROWID + "=" + rowId, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	/**
	 * Return a Cursor positioned at the defined Parameter
	 */
	public Cursor fetchParameterByKey(String key) throws SQLException {
		Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] {
				KEY_ROWID, KEY_PARAMKEY, KEY_PARAMVALUE },
				KEY_PARAMKEY + " = '" + key + "'", null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
 }
